package Servlet;

import Service.CaptchaStoreService;
import utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Su
 * @Date 2025/4/30 16:16
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/auth/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 生成验证码
        CaptchaUtil.Captcha captcha = CaptchaUtil.generateCaptcha();

        // 存储到会话
        HttpSession session = req.getSession();
        CaptchaStoreService.storeCaptcha(session.getId(), captcha.getText());

        // 返回图片
        resp.setContentType("image/jpeg");
        resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Expires", "0");

        try (ServletOutputStream out = resp.getOutputStream()) {
            out.write(captcha.getImageData());
        }
    }
}
